using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using CodeStory.Core.ObjectEntity;
using CodeStory.Core.UI;
using Activa.CoolStorage;

namespace CodeStory.WebApplication.Modules.Core.Admin
{
	public partial class RoleManager : Portlet
	{
		protected override void OnInit(EventArgs e) {
			Load += new EventHandler(RoleManager_Load);
			roleGridView.RowCommand += new GridViewCommandEventHandler(GridView_RowCommand);
			okButton.Click += new EventHandler(OKButton_Click);
			cancelButton.Click += new EventHandler(CancelButton_Click);
			base.OnInit(e);
		}

		void CancelButton_Click(object sender, EventArgs e) {
			//throw new Exception("The method or operation is not implemented.");
			RoleIDValue = string.Empty;
			rolenameTextBox.Text = string.Empty;
			descriptionTextBox.Text = string.Empty;
		}

		void OKButton_Click(object sender, EventArgs e) {
			//throw new Exception("The method or operation is not implemented.");
			RoleObject role;
			if (IsEditing) {
				role = RoleObject.Read(new Guid(roleidHiddenField.Value));
			} else {
				role = RoleObject.New();
				role.RoleID = Guid.NewGuid();
			}
			role.RoleName = rolenameTextBox.Text;
			role.Description = descriptionTextBox.Text;
			role.Save();
			BindRoles();
		}

		void GridView_RowCommand(object sender, GridViewCommandEventArgs e) {
			string roleid = e.CommandArgument.ToString();
			RoleObject role = RoleObject.Read(new Guid(roleid));
			switch (e.CommandName) {
				case "EditRole":
					RoleIDValue = roleid;
					rolenameTextBox.Text = role.RoleName;
					descriptionTextBox.Text = role.Description;
					break;
				case "DeleteRole":
					role.Delete();
					BindRoles();
					CSList<RoleResourceObject> resourceList = RoleResourceObject.List("RoleID=@RoleID","@RoleID",role.RoleID);
					resourceList.DeleteAll();
					CSList<UserInRoleObject> userList = UserInRoleObject.List("RoleID=@RoleID","RoleID",role.RoleID);
					userList.DeleteAll();
					break;
			}
		}

		private bool IsEditing {
			get { return !string.IsNullOrEmpty(roleidHiddenField.Value); }
		}

		private string RoleIDValue {
			set {
				roleidHiddenField.Value = value;
				okButton.Text = IsEditing ? "Update" : "Create Role";
			}
		}

		void RoleManager_Load(object sender, EventArgs e) {
			//throw new Exception("The method or operation is not implemented.");
			if (!IsPostBack) {
				BindRoles();
			}

			okButton.Text = IsEditing ? "Update" : "Create Role";
		}

		private void BindRoles() {
			CSList<RoleObject> list = RoleObject.List();
			roleGridView.DataSource = list;
			roleGridView.DataBind();
		}
	}
}